from PySide2.QtCore import QObject, Signal, Slot

from random import random

class DeviceRecieveWorker(QObject):
    gotbuffer = Signal(bytearray)
    timeout = Signal()

    def __init__(self, device, framelength, head):
        super().__init__()
        self.device = device
        self.head = bytes.fromhex(head.replace(" ", ""))
        self.framelength = framelength
    
    def checkhead(self, buffer):
        for n, b in enumerate(self.head):
            print(hex(b), hex(buffer[n]))
            if buffer[n] != b:
                break
        else:
            return True
        return False
    
    def droprear(self):
        buffer = ''
        while not buffer:
            buffer = self.device.read(self.framelength)
        for k in range(len(buffer) - len(self.head)):
            if self.checkhead(buffer[k:]):
                break
        buffer = self.device.read(k)

    @Slot()
    def run(self):
        self.droprear()
        while True:
            try:
                buffer = self.device.read(self.framelength)
            except:
                self.timeout.emit()
                break
            if buffer:
                # random check
                if random() < 0.01:
                    self.droprear()
                self.gotbuffer.emit(buffer)
